 <template>
  <el-dialog title="分配角色" :visible="showRoleDialog" @close="handleClose" @open="loadAllRoles">
    <!-- 角色列表 -->
    <el-checkbox-group v-model="roleIds">
        <!-- 复选框的值靠label获取 -->
        <el-checkbox v-for="item in allRoles" :key="item.id" :label="item.id">{{item.name}}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="assignRole">确定</el-button>
      <el-button size="small" @click='handleClose'>取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { reqGetRoleList } from '@/api/setting.js'
import { getDetailInfo as reqGetUserDetailById } from '@/api/user'
import {reqAssignRoles} from '@/api/employees'

export default {
  name: 'AssignRole',
  props: {
      // 用户id
    userId: {
      type: String,
      required: true
    },
    // 控制弹窗
    showRoleDialog: {
      type: Boolean,
      required: true
    }
  },
  data(){
      return{
          //选中的角色列表
          roleIds:[],
          //所有的角色列表
          allRoles:[]
      }
  },
  methods: {
      
    //确定按钮 给用户分配新的角色表单提交
    async assignRole () {
      const ret = await reqAssignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      if (ret.code === 10000) {
        // 分配角色成功，提示一下，关闭弹窗
        this.$message.success('分配角色成功')
        this.handleClose()
      }
    },

   loadAllRoles () {
      this.loading = true
      // 获取该用户默认拥有的角色
      const info = reqGetUserDetailById(this.userId)
      // 获取所有的角色列表数据
      const ret = reqGetRoleList({ page: 1, pagesize: 10000 })
      // 并发触发多个异步任务
      Promise.all([info, ret]).then(result => {
        this.roleIds = result[0].data.roleIds
        this.allRoles = result[1].data.rows
      }).catch(() => {
        this.$message.error('获取角色列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 控制窗口关闭 有 update 就有asny
    handleClose () {
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>
